# !/usr/bin/env python
# -*- encoding: utf-8 -*-
# @Author : 大野

from interface.excel.geturlParams import geturlParams
import configparser
import os
from interface.testCase.asserts.checkResult import CheckResult
from common.log import Log
from interface.common.paramsplit import Paramsplit
from interface.common.resultchange import Resultchange
from interface.common.headers import GetToken
from common.caseregfun import *

cr = CheckResult()
path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
config = configparser.ConfigParser()
config.read(path + '/config/cookie.ini', encoding='utf-8')
config.read(path + '/config/config.ini', encoding='utf-8')
url = geturlParams().get_Url()  # 调用我们的geturlParams获取我们拼接的URL

logger = Log()
ps = Paramsplit()
rch = Resultchange()
get_token = GetToken()

null = None


class Testtest:
    def __init__(self):
        logger.info("自动化用例执行开始")
        # 格式 {"case_1":{response001},"case_2":{response002}} 存储所有的接口响应数据，用来关联使用
        self.relationvalue = {}
        self.testresult = []  # 存储测试结果
        self.apiresponse = {}

    def relation_number(self, relationindex):
        indexs = str(relationindex).split(',')
        tmpindex = []
        for index in indexs:
            try:
                tmpindex.append(f"case_{int(index)}")
            except Exception as e:
                logger.info(f"检查索引{index}是否正确{e.args}")
        return tmpindex

    def execase(self, project, caseone):
        global apiresponse
        case = eval(caseone)
        sql = f'select * from project_url_mapping where project_id = {project}'
        from common.database import DataBase as db
        rep = db().test_platform([sql])
        if not rep:
            return {
                "success": "false",
                "response": "未创建域名配置",
                "responseTime": str(0)}
        for i in rep:
            if i["case_mapping_name"] == case["case_path"]:
                headers = i['header']
                path = str(i["case_path_url"]) + str(case["case_url"])
                apiresponse = cr.checkresult(
                    path, i["relation"], headers, case, project)
            else:
                pass
        if case['case_relation_param']:
            # 参数提取
            relationresult = extractparam(
                case["case_relation_param"], apiresponse[1])
            if relationresult:
                self.relationvalue[f"case_{case['case_id']}"] = relationresult
                return apiresponse[0]
            else:
                return apiresponse[0]
        else:
            return apiresponse[0]

    def testInterface(self, project, casesuite):
        count = 1
        for case in casesuite:
            if isinstance(case, list):
                for case2 in case:
                    self.__start_case(case2, project, count)
            else:
                self.__start_case(case, project, count)
            count += 1
        return self.testresult

    def __start_case(self, case, project, count):
        logger.info(f"当前变量参数:{self.relationvalue}")
        case = regparam(case, self.relationvalue)
        logger.info(f"第 {count} 条用例开始执行")
        response = self.execase(project, case)
        logger.info(f"第 {count} 条用例执行结束")
        cas = eval(case)
        if response:
            resp = {**response, **cas}
            self.testresult.append(resp)
        else:
            pass
